/*java jdk 1.7+
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''*/

package com.zxy.tcp;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Date;

import com.zxy.business.Analyse_Data;
import com.zxy.common.Com_Para;

public class ClientRegHandler extends Thread
{
	@SuppressWarnings("unused")
	private SocketAddress	sadd	= null;
	private Socket			socket	= null;

	public void run()
	{
		this.setName("ClientRegHandler_zxyong");
		if(!Com_Para.ServerIP.equals(""))
		{
			sadd = InetSocketAddress.createUnresolved(Com_Para.ServerIP,Com_Para.ServerPort);
			Analyse_Data ad = new Analyse_Data();
			try
			{
				if(java.util.Objects.equals(socket,null))
				{
					socket = new Socket(Com_Para.ServerIP,Com_Para.ServerPort);
					ad.SendReg(socket);
				}
				socket.isBound();
				socket.setKeepAlive(true);
			}
			catch(Exception dd)
			{
			}
			Date rightStart = new Date();
			while(true)
			{
				long temp = new Date().getTime() - rightStart.getTime();
				try
				{
					if(!java.util.Objects.equals(socket,null) && socket.isConnected()
							&& !socket.isClosed())
					{
						Com_Para.clientSocket = socket;
						Com_Para.htServSockets.put("clientSocket",socket);
					}
					if((temp / 1000) > 300)
					{
						try
						{
							if(java.util.Objects.equals(socket,null))
							{
								socket = new Socket(Com_Para.ServerIP,Com_Para.ServerPort);
							}
							ad.SendReg(socket);
							socket.isBound();
							socket.setKeepAlive(true);
							Com_Para.clientSocket = socket;
						}
						catch(Exception dd)
						{
							Com_Para.clientSocket = null;
							Com_Para.htServSockets.remove("clientSocket");
						}
						rightStart = new Date();
					}else
					{
						Com_Para.htServSockets.remove("clientSocket");
						Com_Para.clientSocket = null;
					}
					Thread.sleep(1000);
				}
				catch(Exception e)
				{
					if((temp / 1000) > 300)
					{
						try
						{
							socket = null;
							socket = new Socket(Com_Para.ServerIP,Com_Para.ServerPort);
							ad.SendReg(socket);
							socket.isBound();
							socket.setKeepAlive(true);
							Com_Para.clientSocket = socket;
						}
						catch(Exception dd)
						{
							Com_Para.clientSocket = null;
							Com_Para.htServSockets.remove("clientSocket");
						}
						rightStart = new Date();
					}
				}
			}
		}
	}

	public Boolean isServerClose(Socket socket)
	{
		try
		{
			socket.sendUrgentData(0);
			// 发送1个字节的紧急数据，默认情况下，服务器端没有开启紧急数据处理，不影响正常通信
			return false;
		}
		catch(Exception se)
		{
			return true;
		}
	}
}